/**
 * 不能依赖自己的模块
 */
layui.define(['jquery', 'table', 'md5', 'conf'], function (exports) {
    const {jquery: $, md5, table, conf} = layui;

    exports('func', {
        /**
         * 地址拼接函数
         * @param path
         * @param params
         * @param api
         */
        url: function (path, params = {}, api = false) {
            var url = location.href.replace(location.hash, '');
            if (!api) {
                url += '#' + path;
            } else {
                url += path;
            }

            if (Object.keys(params).length) {
                url += '?' + $.param(params);
            }
            return url;

        },
        /**
         * 表单自动填充
         * @param formData
         */
        assign: function (formData) {
            var input = '', form = layui.form;
            for (var i in formData) {
                if (!$('.field-' + i)[0]) {
                    continue;
                }
                if ($('.field-' + i)[0].nodeName.toLowerCase() == 'textarea') {
                    input = $('.field-' + i);
                    input.text(formData[i]);
                    continue;
                }

                switch ($('.field-' + i).attr('type')) {
                    case 'select':
                        input = $('.field-' + i).find('option[value="' + formData[i] + '"]');
                        input.prop("selected", true);
                        break;
                    case 'radio':
                        input = $('.field-' + i + '[value="' + formData[i] + '"]');
                        input.prop('checked', true);
                        break;
                    case 'checkbox':
                        if (!formData[i]) {
                            continue;
                        }
                        input = $('.field-' + i);
                        input.prop('checked', true);
                        break;

                    case 'img':
                        if (formData[i]) {
                            input = $('.field-' + i);
                            input.attr('src', formData[i]);
                        }
                        break;

                    default:
                        input = $('.field-' + i);
                        input.val(formData[i]);
                        break;
                }

                if (input.attr('data-disabled')) {
                    input.prop('disabled', true);
                }

                if (input.attr('data-readonly')) {
                    input.prop('readonly', true);
                }
            }
            form.render();
        },
        /**
         * 发送消息
         * @param from
         * @param data
         */
        postMessage: function (from, data) {
            parent.window.dispatchEvent(new CustomEvent(from, {
                detail: data,
                bubbles: true,    //是否冒泡
                cancelable: false //是否取消默认事件
            }));
        },
        /**
         * 接收消息
         * @param from
         * @param callback
         * @param once 是否只接收一次
         */
        receiveMessage: function (from, callback, once = false) {
            var fn = function (event) {

                callback(event.detail);

                //接收到一次就去除监听
                once && parent.removeEventListener(event.type, fn);
            };

            parent.window.addEventListener(from, fn);
        },
        tableCheckBoxFields: function (target, field = 'id') {
            var checkStatus = table.checkStatus(target);
            var data = checkStatus.data;
            if (data.length === 0) {
                parent.layer.msg('请选择要操作的项');
                return;
            }
            var values = [];
            for (var i = 0; i < data.length; i++) {
                values.push(data[i][field]);
            }
            return values;
        },
        /**
         * 绑定图片放大预览
         **/
        bindImgViewer: function () {
            var interval = setInterval(function () {
                if ($('.viewer-area img:not([lay-viewer])').length) {
                    $('.viewer-area img:not([lay-viewer])').each(function (index, elem) {
                        console.log(elem);
                        $(elem).attr('lay-viewer', elem.src);
                        new Viewer($(this)[0], {
                            url: 'lay-viewer'
                        });
                    })
                } else {
                    clearInterval(interval);
                }
            }, 200);
        },
        /**
         * 获取tree所有id集合
         * @param tree
         * @param urls
         */
        getTreeCheckedIds: function (tree, urls = []) {
            const that = this;
            tree.forEach(function (node) {
                if (node.children) {
                    urls = urls.concat(that.getTreeCheckedIds(node.children));
                }
                if (node.id && node.id !== "") {
                    urls.push(node.id);
                }
            })
            return urls;
        },
        /**
         * 获取网站当前路经过
         */
        getRootPath: function () {
            // 获取当前网址，如：http://localhost/WebCourse/jsp/login/login.jsp
            var curWwwPath = window.document.location.href;
            // 获取主机地址之后的目录，如： WebCourse/jsp/login/login.jsp
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            // 获取主机地址，如： http://localhost
            var localhostPaht = curWwwPath.substring(0, pos);
            // 获取带"/"的项目名，如：/WebCourse
            var projectName = pathName.substring(0,
                pathName.substr(1).indexOf('/') + 1);
            return (localhostPaht + projectName);
        },
        /**
         * 获取Hash值
         * @returns {{}}
         */
        param: function () {
            let params = {};
            let tmp = window.location.hash.split("?");
            if (!tmp[1]) {
                return params;
            }

            let vars = tmp[1].split("&");
            for (let i = 0; i < vars.length; i++) {
                let pair = vars[i].split("=");
                params[pair[0]] = pair[1];
            }
            return params;
        },
        /**
         * 获取Get参数
         * @returns {{}}
         */
        query: function () {
            var queryParam = {};
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                queryParam[pair[0]] = pair[1];
            }

            return queryParam;
        },
        snake2camel(data) {
            if (typeof data !== 'object' || !data) {
                return data
            }
            if (Array.isArray(data)) {
                return data.map(item => this.snake2camel(item))
            }
            const newData = {}
            for (const key in data) {
                const newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
                newData[newKey] = this.snake2camel(data[key])
            }
            return newData
        },
        camel2snake(data) {
            if (typeof data !== 'object' || !data) {
                return data
            }
            if (Array.isArray(data)) {
                return data.map(item => this.camel2snake(item))
            }
            const newData = {}
            for (const key in data) {
                const newKey = key.replace(/([A-Z])/g, (p, m) => `_${m.toLowerCase()}`)
                newData[newKey] = this.camel2snake(data[key])
            }
            return newData
        },
        changeFavicon: function (src) {
            var head = document.getElementsByTagName('head')[0];

            var link = document.createElement('link'),
                oldLink = document.getElementById('dynamic-favicon');
            link.id = 'dynamic-favicon';
            link.rel = 'shortcut icon';
            link.href = src;
            if (oldLink) {
                head.removeChild(oldLink);
            }
            head.appendChild(link);
        },
        /**
         * 加载script
         */
        loadScript: function (options) {
            options = $.extend(true, {
                //异步
                async: true,
                //编码
                charset: 'utf-8',
                //地址
                url: "",
                //检查是否已加载
                check: function () {
                },
                //已加载回调
                success: function () {
                },
            }, options);

            options.url += function () {
                var version = layui.config.version === true
                    ? layui.config.v : (layui.config.version || '');
                return version ? ('?v=' + version) : '';
            }();

            //检查是否已经存在
            if($("head script[src='" + options.url + "']").length || options.check()){
                options.success();
                return;
            }

            var node = doc.createElement('script');
            node.async = options.async;
            node.charset = options.charset;

            node.src = options.url + function () {
                var version = layui.config.version === true
                    ? layui.config.v : (layui.config.version || '');
                return version ? ('?v=' + version) : '';
            }();




            head.appendChild(node);
            if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) {
                node.attachEvent('onreadystatechange', function (e) {
                    onScriptLoad(e, url);
                });
            } else {
                node.addEventListener('load', function (e) {
                    onScriptLoad(e, url);
                }, false);
            }


            function onScriptLoad(e, url) {
                var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/
                if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
                    (function poll() {
                        if (++timeout > config.timeout * 1000 / 4) {
                            throw new Error("Script加载失败，地址为" + url)
                        }

                        !options.check() ? options.success() : setTimeout(poll, 4);
                    }());
                }
            }

        }
    });
});
